<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: Install.php 355 2010-02-01 05:29:23Z steen.rabol@gmail.com $
 *
 */

Prado::using('Application.Common.Data.PortalHelpRecord');

class Install extends PortalSystemPage
{
	const CONFIG_FILE		= 'Application.Data.Settings';

	private $_culture		= 'en';
	private $_helpculture	= 'en';

	public function onPreInit($param)
	{
		$this->Application->Mode = TApplicationMode::Debug;
		parent::onPreInit($param);

		$langloaded	= false;
		$lng		= $this->Request->UserLanguages;

		foreach($lng as $ulang)
		{
			$langfile = $this->Application->PortalBasePath . '/protected/Data/lang/' . $ulang . '.xml';

			if(file_exists($langfile))
			{
				$this->_culture						= $ulang;
				$this->Application->LanguageStrings	= $this->loadTranslation($langfile);
				$this->Application->Culture			= $ulang;
				$langloaded							= true;
				break;
			}
		}

		if(!$langloaded)
		{
			// Load english language...
			$langfile = $this->Application->PortalBasePath . '/protected/Data/lang/en.xml';
			$this->Application->LanguageStrings = $this->loadTranslation($langfile);
		}

		$this->MasterClass	= 'Application.Layouts.Portal.Default.PortalSystemLayout';
		$this->Theme		= 'Portal/Default';
	}

	public function onLoad($param)
	{
		$this->Title	= Prado::localize("Prado Portal installation");

	}

	public function IWCompleted($sender,$param)
	{
		$this->CreateDbTables();
		$this->CreateDefaultData();
		$this->ImportLanguage();
		$this->ImportHelpPages();
		$this->CreateAdminUser();
		$this->SaveSiteConfig();
	}

	public function IWNextStep($sender,$param)
	{
		switch($param->CurrentStepIndex)
		{
			case 2:
				$this->LoadSiteConfig();
				break;
		}
	}

	public function ImportLanguage()
	{
		try
		{
			$cdb = new TDbConnection('mysql:host=' . $this->DBHost->Text . ';dbname=' . $this->DBDatabase->Text , $this->DBUser->Text,$this->DBPassword->Text);
			$cdb->Active = true;
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided") . "<br /><br />Db error: " . $e->getMessage());
		}

		// Import language strings
		$langfile	= $this->Application->PortalBasePath . '/protected/Data/lang/en.xml';
		$lstrings	= $this->loadlangfile($langfile);

		if($lstrings !== false && is_array($lstrings) && count($lstrings) > 1)
		{
			try
			{
				$i = 0;
				$sql = "insert into tbllangstrings(culture,lkey,fromvalue,tovalue) values";
				foreach($lstrings as $ls)
				{
					$lkey		= $cdb->quoteString($ls[1]);
					$fromvalue	= $cdb->quoteString($ls[2]);
					$tovalue	= $cdb->quoteString($ls[3]);
					$culture	= 'en';
					$sql .= "('$culture',$lkey,$fromvalue,$tovalue),";

					if($i == 300)
					{
						$sql = substr($sql,0,-1);
						$cdb->createCommand($sql)->execute();
						$sql = "insert into tbllangstrings(culture,lkey,fromvalue,tovalue) values";
					}

					$i++;
				}

				$sql = substr($sql,0,-1);
				$cdb->createCommand($sql)->execute();
			}
			catch(Exception $e)
			{
				PortalUtil::fatalError(Prado::localize("Failed to import 'en' language strings") . "<br /><br />Db error: " . $e->getMessage());
			}
		}

		$langfile	= $this->Application->PortalBasePath . '/protected/Data/lang/da.xml';
		$lstrings	= $this->loadlangfile($langfile);

		if($lstrings !== false && is_array($lstrings) && count($lstrings) > 1)
		{
			try
			{
				$i		= 0;
				$sql	= "insert into tbllangstrings(culture,lkey,fromvalue,tovalue) values";
				foreach($lstrings as $ls)
				{
					$lkey		= $cdb->quoteString($ls[1]);
					$fromvalue	= $cdb->quoteString($ls[2]);
					$tovalue	= $cdb->quoteString($ls[3]);
					$culture	= 'da';
					$sql .= "('$culture',$lkey,$fromvalue,$tovalue),";

					if($i == 300)
					{
						$sql = substr($sql,0,-1);
						$cdb->createCommand($sql)->execute();
						$sql = "insert into tbllangstrings(culture,lkey,fromvalue,tovalue) values";
					}

					$i++;
				}
				
				$sql = substr($sql,0,-1);
				$cdb->createCommand($sql)->execute();

			}
			catch(Exception $e)
			{
				PortalUtil::fatalError(Prado::localize("Failed to import 'da' language strings") . "<br /><br />Db error: " . $e->getMessage());
			}
		}
	}

	public function ImportHelpPages()
	{
		$helpfile	= $this->Application->PortalBasePath . '/protected/Data/lang_help/help_da.xml';
		$helppages	= $this->loadHelpFile($helpfile);

		if($helppages && count($helppages) > 0)
		{
			$this->_insertHelpPages($helppages);
		}

		$helpfile	= $this->Application->PortalBasePath . '/protected/Data/lang_help/help_en.xml';
		$helppages	= $this->loadHelpFile($helpfile);

		if($helppages && count($helppages) > 0)
		{
			$this->_insertHelpPages($helppages);
		}
	}

	private function _insertHelpPages($pages)
	{
		try
		{
			$cdb = new TDbConnection('mysql:host=' . $this->DBHost->Text . ';dbname=' . $this->DBDatabase->Text , $this->DBUser->Text,$this->DBPassword->Text);
			$cdb->Active = true;
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided") . "<br /><br />Db error: " . $e->getMessage());
		}

		try
		{
			foreach($pages as $page)
			{
				$pagename	= $page[1];
				$culture	= $this->_helpculture;
				$content	= $cdb->quoteString($page[3]);
				$title		= $cdb->quoteString($page[2]);

				$sql = "insert into tblhelp(pagename,culture,content,title) values('$pagename','$culture',$content,$title)";
				$cdb->createCommand($sql)->execute();
			}
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Failed to import help pages") . "<br /><br />Db error: " . $e->getMessage());
		}
	}

	public function validateDbInformation($sender, $param)
	{
		try
		{
			$cdb			= new TDbConnection('mysql:host=' . $this->DBHost->Text . ';dbname=' . $this->DBDatabase->Text , $this->DBUser->Text,$this->DBPassword->Text);
			$cdb->Active	= true;
			$param->IsValid	= true;
		}
		catch(Exception $e)
		{
			$param->IsValid = false;
		}
	}

	public function CheckDbInformation()
	{
		try
		{
			$cdb			= new TDbConnection('mysql:host=' . $this->DBHost->Text . ';dbname=' . $this->DBDatabase->Text , $this->DBUser->Text,$this->DBPassword->Text);
			$cdb->Active	= true;
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided<br />Please go back and correct it") . "<br /><br />Db error: " . $e->getMessage());
		}

		if(!$cdb->Active)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided<br />Please go back and correct it") . " <br /><br />Db error:" . $e->getMessage());
		}
	}

	public function CreateDbTables()
	{
		$errors	= array();

		try
		{
			$cdb = new TDbConnection('mysql:host=' . $this->DBHost->Text . ';dbname=' . $this->DBDatabase->Text , $this->DBUser->Text,$this->DBPassword->Text);
			$cdb->Active = true;
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided<br />Please go back and correct it")  . " " . $e->getMessage());
		}

		if(!$cdb->Active)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided<br />Please go back and correct it"));
		}

		$installfile = dirname($this->getRequest()->getApplicationFilePath()). '/' . "protected/Pages/Install/MySQL.php";
		if(!file_exists($installfile))
		{
			PortalUtil::fatalError(Prado::localize("Could not find file with database table information."));
		}
		else
		{
			include_once($installfile);

			// Read the file and execute the SQL
			if(is_array($drop_table))
			{
				// First we drop the tables
				foreach($drop_table as $dtsql)
				{
					try
					{
						$cdb->createCommand(trim($dtsql))->execute();
					}
					catch(Exception $e)
					{
						$errors[] = $e->getMessage();
					}
				}
			}

			if(is_array($create_table))
			{
				// let's create the tables
				foreach($create_table as $ctsql)
				{
					try
					{
						$cdb->createCommand(trim($ctsql))->execute();
					}
					catch(Exception $e)
					{
						$errors[] = $e->getMessage();
					}
				}
			}
		}

		if(count($errors) !== 0)
		{
			PortalUtil::fatalError($errors);
		}
	}

	public function CreateDefaultData()
	{
		$errors	= array();

		try
		{
			$cdb			= new TDbConnection('mysql:host=' . $this->DBHost->Text . ';dbname=' . $this->DBDatabase->Text , $this->DBUser->Text,$this->DBPassword->Text);
			$cdb->Active	= true;
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided<br />Please go back and correct it")  . " " . $e->getMessage());
		}

		if(!$cdb->Active)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided<br />Please go back and correct it"));
		}

		// Create default data
		try
		{
			$cdb->createCommand("insert into tblroles(name) values('Guest')")->execute();
			$cdb->createCommand("insert into tblroles(name) values('User')")->execute();
			$cdb->createCommand("insert into tblroles(name) values('Admin')")->execute();
		}
		catch(Exception $e)
		{
			$errors[] = $e->getMessage();
		}

		// Create potlets
		try
		{
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('AccountPortlet','" . Prado::localize('Account functions portlet'). "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('AdminPortlet','" . Prado::localize('Administrator portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('DownloadPortlet','" . Prado::localize('Download portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('HTMLPortlet','" . Prado::localize('WYSIWG text portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('ImagePortlet','" . Prado::localize('Display image portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('JsCookMenuPortlet','" . Prado::localize('Js dropdown menu portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('LanguagePortlet','" . Prado::localize('Language selection portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('LoginPortlet','" . Prado::localize('Login portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('LXListMenuPortlet','" . Prado::localize('Local list based menu portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('NewsPortlet','" . Prado::localize('News portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('OnlineUserInfoPortlet','" . Prado::localize('User information portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('PollPortlet','" . Prado::localize('Poll portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('SearchPortlet','" . Prado::localize('Search portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('SendMailPortlet','" . Prado::localize('Send mail') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('SimpleTextPortlet','" . Prado::localize('Simple text') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('SiteMapPortlet','" . Prado::localize('Sitemap') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('SWFObjectPortlet','" . Prado::localize('Display flash movie') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('SyndicatePortlet','" . Prado::localize('Syndicate Portlet') . "','1')")->execute();
			$cdb->createCommand("insert into tblportlets(name,displayname,active) values('XListMenuPortlet','" . Prado::localize('List based menu of active pages portlet') . "','1')")->execute();
		}
		catch(Exception $e)
		{
			$errors[] = $e->getMessage();
		}

		// Add the default page
		try
		{
			$cdb->createCommand("insert into tblpages(name,active,created,modified,locked,displayname,layoutname,createdby,fullpath,metakeywords,metadescription) values('Home','1','" . time() . "','" . time() . "','0','Home','PortalLayout','1','Home','','')")->execute();
		}
		catch(Exception $e)
		{
			$errors[] = $e->getMessage();
		}

		try
		{
			// Create 'Home' page and content
			$cdb->createCommand("insert into tblpagecontent(pagename,controlname,portlet,displayorder,active,needlogin,showafterlogin) values('Home','maincontent','HTMLPortlet','1','1','0','1')")->execute();
			$cdb->createCommand("insert into tblpagecontent(pagename,controlname,portlet,displayorder,active,needlogin,showafterlogin) values('Home','rightbar','LoginPortlet','1','1','0','0')")->execute();
			$cdb->createCommand("insert into tblpagecontent(pagename,controlname,portlet,displayorder,active,needlogin,showafterlogin) values('Home','rightbar','AccountPortlet','2','1','1','1')")->execute();
			$cdb->createCommand("insert into tblpagecontent(pagename,controlname,portlet,displayorder,active,needlogin,showafterlogin) values('Home','menuline','JsCookMenuPortlet','1','1','0','1')")->execute();
			// Some default text
			$cdb->createCommand("insert into tblhtmlportlet(id,content) values(1,'<h2>Welcome to Prado Portal</h2>This is the default page')")->execute();

			// Menu
			$sql = "insert into tblsitemenu(name,active,role) values('Main menu',1,0)";
			$cdb->createCommand($sql)->execute();

			// Menu item
			$sql = "insert into tblsitemenuitem(smid,title,page,img,active,role,target,showafterlogin) values(1,'Home','Home','',1,0,'_self',1)";
			$cdb->createCommand($sql)->execute();

			$sql ="insert into tbljscookmenu(id,theme,menuorientation,needlogin,active,name,sitemenuid) values(4,'ThemeGray','hbr',0,1,'',1)";
			$cdb->createCommand($sql)->execute();
		}
		catch(Exception $e)
		{
			$errors[] = $e->getMessage();
		}

		// Default permission
		try
		{
			// Admin Role permissions
			$cdb->createCommand("insert into tblpermissions(selector,value,view,edit) values('role',3,1,1)")->execute();
			// Admin user specific
			$cdb->createCommand("insert into tblpermissions(selector,value,view,edit) values('user',1,1,1)")->execute();

			// Allow 'Guest' group to view Home, and a few system pages
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('Home','role',1,1,0)")->execute();
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('System.NewUser','role',1,1,0)")->execute();
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('System.ForgottenPassword','role',1,1,0)")->execute();
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('System.ErrorReport','role',1,1,0)")->execute();

			// Allow 'User' group to view needed System pages
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('Home','role',2,1,0)")->execute();
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('System.NewUser','role',2,1,0)")->execute();
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('System.ForgottenPassword','role',2,1,0)")->execute();
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('System.EditUser','role',2,1,0)")->execute();
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('System.ErrorReport','role',2,1,0)")->execute();
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('System.InActiveLogin','role',2,1,0)")->execute();
			$cdb->createCommand("insert into tblpermissions(page,selector,value,view,edit) values('System.ViewUser','role',2,1,0)")->execute();
		}
		catch(Exception $e)
		{
			$errors[] = $e->getMessage();
		}

		$sql		= "insert into tbllanguages(name,country,culture,active,displayorder) values";
		// read the file with country codes
		$langfile	= dirname($this->getRequest()->getApplicationFilePath()). '/' . "protected/Pages/Install/langcodes.txt";
		$row		= 1;
		$handle		= fopen($langfile, "r");

		while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
		{
			$name		= $data[1];
			$country	= strtolower(substr($data[0],3,999));
			$culture	= $data[0];

			if($country == "")
			{
				$country = $data[0];
			}

			$sql .= "('$name','$country','$culture','0',$row),";
		}
		fclose($handle);

		try
		{
			$sql = substr($sql,0,-1);
			$cdb->createCommand($sql)->execute();
			$row++;
		}
		catch(Exception $e)
		{
			$errors[] = $e->getMessage();
		}

		try
		{
			$sql = "update tbllanguages set active=1 where culture='en'";
			$cdb->createCommand($sql)->execute();

			$sql = "update tbllanguages set active=1 where culture='da'";
			$cdb->createCommand($sql)->execute();

			// Add version information to the database
			$sql = "insert into tblconfig(name,value,culture) values('portalversion','{$this->Application->PortalVersion()}','en')";
			$cdb->createCommand($sql)->execute();
		}
		catch(Exception $e)
		{

			$errors[] = $e->getMessage() . '<br>' . $cdb->Text;
		}

		if(count($errors) !== 0)
		{
			PortalUtil::fatalError($errors);
		}
	}

	public function CreateAdminUser()
	{
		try
		{
			$cdb = new TDbConnection('mysql:host=' . $this->DBHost->Text . ';dbname=' . $this->DBDatabase->Text , $this->DBUser->Text,$this->DBPassword->Text);
			$cdb->Active = true;
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided<br />Please go back and correct it")  . " " . $e->getMessage());
		}

		$name		= $this->Username->Text;
		$full_name	= $this->FullName->Text;
		$role		= 3; // Admin
		$password	= hash("sha256",$this->Password->Text);
		$vcode		= '';
		$email		= $this->Email->Text;
		$reg_time	= time();
		$status		= 0;
		$sitenews	= 1;

		try
		{
			$sql = "insert into tblusers(name,full_name,role,password,vcode,email,reg_time,status,sitenews) values('$name','$full_name','$role','$password','$vcode','$email','$reg_time','$status','$sitenews')";
			$cdb->createCommand($sql)->execute();
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("faild to create the admin user<br />Please go back and correct it")  . " " . $e->getMessage());
		}

		// Insert the Admin into the SendMailPortlet
		try
		{
			$sql = "insert into tblsendemailportlet(name,email,active) values('$full_name','$email','1')";
			$cdb->createCommand($sql)->execute();
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("faild to create the admin portlet<br />Please go back and correct it")  . " " . $e->getMessage());
		}
	}

	public function LoadSiteConfig()
	{
		try
		{
			$cdb = new TDbConnection('mysql:host=' . $this->DBHost->Text . ';dbname=' . $this->DBDatabase->Text , $this->DBUser->Text,$this->DBPassword->Text);
			$cdb->Active = true;
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided<br />Please go back and correct it")  . " " . $e->getMessage());
		}

		$parameters								= $this->Application->Parameters;
		$this->SiteTitle->Text					= $parameters['SiteTitle'];
		$this->SiteOwner->Text					= $this->FullName->Text;
		$this->AdminEmail->Text					= $this->Email->Text;
		$this->MultipleUser->Checked			= TPropertyValue::ensureBoolean($parameters['MultipleUser']);
		$this->AccountApproval->Checked			= TPropertyValue::ensureBoolean($parameters['AccountApproval']);
		$themes									= PortalUtil::getAvailablePortalThemes();
		$this->ThemeName->DataSource			= $themes;
		$this->ThemeName->dataBind();
		$this->ThemeName->SelectedValue			= (array_search($parameters['ThemeName'],$themes) ? array_search($parameters['ThemeName'],$themes) : 0);

		$adminthemes							= PortalUtil::getAvailableAdminThemes();
		$this->AdminThemeName->DataSource		= $adminthemes;
		$this->AdminThemeName->dataBind();
		$this->AdminThemeName->SelectedValue	= (array_search($parameters['AdminThemeName'],$adminthemes) ? array_search($parameters['AdminThemeName'],$adminthemes) : 0);

		$droles = array();
		$droles[] = array("id" => "0", "name" => Prado::localize("Select"));
		$droles[] = array("id" => "1", "name" => Prado::localize('Guest'));
		$droles[] = array("id" => "2", "name" => Prado::localize('User'));
		$droles[] = array("id" => "3", "name" => Prado::localize('Admin'));

		$this->AdminRole->DataSource = $droles;
		$this->AdminRole->dataBind();
		$this->AdminRole->SelectedValue = 3;

		$this->MinRole->DataSource = $droles;
		$this->MinRole->dataBind();
		$this->MinRole->SelectedValue = 1;

		$this->NewUserRole->DataSource = $droles;
		$this->NewUserRole->dataBind();
		$this->NewUserRole->SelectedValue = 2;

		$this->UseCookieExpire->Checked	= TPropertyValue::ensureBoolean($parameters['UseCookieExpire']);
		$this->CookiePrefix->Text	= $parameters['CookiePrefix'];
		$this->LoginExpire->Text	= $parameters['LoginExpire'];

		$langs = array();
		$langs[] = array("id" => "en", "name" => 'English');
		$langs[] = array("id" => "da", "name" => 'Dansk');

		$this->DefaultLanguage->DataSource	= $langs;
		$this->DefaultLanguage->dataBind();
		$this->DefaultLanguage->SelectedValue = 'en';

		$this->AuthMode->SelectedValue		= TPropertyValue::ensureInteger($parameters['AuthMode']);
		$this->ValidationKey->Text			= "this_is_the_default_validation_key";
	}

	public function SaveSiteConfig()
	{
		try
		{
			$cdb = new TDbConnection('mysql:host=' . $this->DBHost->Text . ';dbname=' . $this->DBDatabase->Text , $this->DBUser->Text,$this->DBPassword->Text);
			$cdb->Active = true;
			$this->lblSaveSiteConfig->Text = Prado::localize("Database information OK<br />Press Next to create default tables and default data");
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Could not connect to the database, using the information you have provided<br />Please go back and correct it")  . " " . $e->getMessage());
		}

		$dom			= new TXmlDocument;
		$dom->Encoding	='utf-8';
		$dom->TagName	='parameters';

		$elements	= $dom->Elements;
		$elements[]	= $this->createParameter('SiteTitle',$this->SiteTitle->Text);
		$elements[]	= $this->createParameter('SiteOwner',$this->SiteOwner->Text);
		$elements[]	= $this->createParameter('AdminEmail',$this->AdminEmail->Text);
		$elements[]	= $this->createParameter('MultipleUser',$this->MultipleUser->Checked);
		$elements[]	= $this->createParameter('AccountApproval',$this->AccountApproval->Checked);
		$elements[]	= $this->createParameter('ThemeName',$this->ThemeName->SelectedItem->Text);
		$elements[]	= $this->createParameter('AdminThemeName',$this->AdminThemeName->SelectedItem->Text);
		$elements[]	= $this->createParameter('AdminRole',$this->AdminRole->getSelectedValue());
		$elements[]	= $this->createParameter('MinRole',$this->MinRole->getSelectedValue());
		$elements[]	= $this->createParameter('NewUserRole',$this->NewUserRole->getSelectedValue());
		$elements[]	= $this->createParameter('PortalLayout','PortalLayout');
		$elements[]	= $this->createParameter('PortalAdminLayout','AdminLayout');
		$elements[]	= $this->createParameter('DbType','MySQL');
		$elements[]	= $this->createParameter('DbHost',$this->DBHost->Text);
		$elements[]	= $this->createParameter('DbDatabase',$this->DBDatabase->Text);
		$elements[]	= $this->createParameter('DbUser',$this->DBUser->Text);
		$elements[]	= $this->createParameter('DbPassword',$this->DBPassword->Text);
		$elements[]	= $this->createParameter('UseCookieExpire', $this->UseCookieExpire->Checked);
		$elements[]	= $this->createParameter('CookiePrefix', $this->CookiePrefix->Text);
		$elements[]	= $this->createParameter('LoginExpire', $this->LoginExpire->Text);
		$elements[]	= $this->createParameter('RunMode',"Normal");
		$elements[]	= $this->createParameter('DefaultLanguage', $this->DefaultLanguage->SelectedValue);
		$elements[]	= $this->createParameter('AuthMode',$this->AuthMode->getSelectedValue());
		$elements[]	= $this->createParameter('ValidationKey',$this->ValidationKey->Text);
		$elements[] = $this->createParameter('IgnoreInstallDir', '1');
		$elements[] = $this->createParameter('TrackOnlineUsers','0');
		$elements[] = $this->createParameter('TrackUserActivity','0');
		$elements[]	= $this->createParameter('AppMode','2');
		$elements[]	= $this->createParameter('NewAccountAction','1');
		$elements[] = $this->createParameter('PortalVersion',$this->Application->PortalVersion());
		$elements[] = $this->createParameter('GridPageSize','20');

		try
		{
			$dom->saveToFile(Prado::getPathOfNamespace(self::CONFIG_FILE,'.xml'));
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError(Prado::localize("Could not save the settings<br />Please go back and correct it")  . " " . $e->getMessage());
		}
	}

	private function createParameter($id,$value)
	{
		$element=new TXmlElement('parameter');
		$element->Attributes['id']=$id;
		$element->Attributes['value']=TPropertyValue::ensureString($value);
		return $element;
	}

	private function DeleteInstallDir($dir)
	{
		$current_dir = @opendir($dir);
		while($entryname = readdir($current_dir))
		{
			if(is_dir("$dir/$entryname") and ($entryname != "." and $entryname!=".."))
			{
				$this->DeleteInstallDir("${dir}/${entryname}",true);
			}
			elseif($entryname != "." and $entryname!="..")
			{
				@unlink("${dir}/${entryname}");
			}
		}

		@closedir($current_dir);
		@rmdir($dir);
	}

	public function cleanandgo($sender, $param)
	{
		if($this->DeleteInstallDir->Checked)
		{
			$this->DeleteInstallDir($this->Application->PortalBasePath . "/protected/Pages/Install");
		}

		$this->gotoPage($this->Service->DefaultPage);
	}

	public function disableNext()
	{
		$ctrl = $this->Master->findcontrol("NextStep");
		if($ctrl)
		{
			$ctrl->Visible = false;
		}
	}

	public function loadTranslation($filename)
	{
		$XML = simplexml_load_file($filename);

		if(!$XML)
		{
			return false;
		}

		$langstrings		= $XML->language;
		$attr				= $langstrings->attributes();
		$this->_culture		= (string)$attr->culture;
		$translationStrings	= $XML->xpath('//string');
		$translations		= array();

		foreach($translationStrings as $string)
		{
			$attr = $string->attributes();
			$translations[(string)$string->fromvalue] = (string)$string->tovalue;
		}
		return $translations;
	}

	public function loadlangfile($filename)
	{
		$XML = simplexml_load_file($filename);

		if(!$XML)
		{
			return false;
		}

		$langstrings		= $XML->language;
		$attr				= $langstrings->attributes();
		$this->_culture		= (string)$attr->culture;
		$translationStrings = $XML->xpath('//string');
		$translations		= array();

		foreach($translationStrings as $string)
		{
			$attr = $string->attributes();
			$translations[]	= array
								(
									(string)$attr->id,
									(string)$attr->lkey,
									(string)$string->fromvalue,
									(string)$string->tovalue
								);
		}

		return $translations;
	}

	public function loadHelpFile($filename)
	{
		$XML = simplexml_load_file($filename);
		if(!$XML)
		{
			return false;
		}

		// Get culture from file
		foreach($XML as $h)
		{
			$a = $h->attributes();
			$this->_helpculture	= (string)$a->culture;
			break;
		}

		$translationStrings = $XML->xpath('//helppage');
		$translations = array();

		foreach($translationStrings as $string)
		{
			$attr = $string->attributes();
			$translations[] = array((string)$attr->id,(string)$string->pagename,(string)$string->title,(string)$string->content);
		}

		return $translations;
	}

	/*
	** Properties
	**
	*/

	public function getCulture()
	{
		return $this->_culture;
	}
}
?>